﻿using System.Windows.Forms;
using System;
using UtfprLibrary.Windows.Forms.Exceptions;

namespace UtfprLibrary.Windows.Forms.Extensions {
    public static class UtfprControlExtensions {
        public static bool IsBindibleFrom(this Control control, UtfprBindingNavigatorBase navigator) {
            try {
                if (navigator == null) {
                    throw new ArgumentNullException("navigator cannot be null.");
                }

                if (navigator.DataSource == null) {
                    throw new ArgumentNullException("DataSource cannot be null.");
                }

                if (!(navigator.DataSource is BindingSource)) {
                    throw new ArgumentNullException("DataSource is not a BindingSource.");
                }

                if (control is DataGridView) {
                    return navigator.DataSource == (control as DataGridView).DataSource;
                }

                if (control is UtfprLookupFieldBase) {
                    return (control as UtfprLookupFieldBase).LookupSource == navigator.DataSource;
                }

                if (control.DataBindings.Count > 0) {
                    return (control.DataBindings[0].DataSource as BindingSource).DataMember == (navigator.DataSource as BindingSource).DataMember;
                }

                return false;
            } catch (Exception ex) {
                throw new UtfprWFCoreExtensionsException("", ex);
            }
        }

        public static bool IsBindible(this Control control) {
            try {
                if (control is DataGridView) {
                    return (control as DataGridView).DataSource != null;
                }

                if (control is UtfprLookupFieldBase) {
                    return (control as UtfprLookupFieldBase).LookupSource != null;
                }

                return control.DataBindings.Count > 0;
            } catch (Exception ex) {
                throw new UtfprWFCoreExtensionsException("", ex);
            }
        }
    }
}
